package com.auxgroup.smarthome.event;


import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.constant.cache.CachedConsant;
import com.auxgroup.smarthome.entity.DeviceInfoEntity;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.repo.AppFilterFaultRepo;
import com.auxgroup.smarthome.repo.DeviceInfoEntityRepo;
import com.auxgroup.smarthome.snoti.events.IPushEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 *  上线以及上线时间同步
 * 上线事件
 * @Author: laiqiuhua.
 * @Date: 2017/9/4 13:32.
 */
@Component
public class OnlineEvent implements IPushEvent {
    @Autowired
    private DeviceInfoEntityRepo deviceInfoEntityRepo;

    @Autowired
    private AppFilterFaultRepo appFilterFaultRepo;

    @Autowired
    private ObjectRedis objectRedis;

    private final String pathKey = CachedConsant.DEVICE_FILTER_FAULT_PREFIX;

    @Override
    public void callback(String message) {
        JSONObject msg = JSONObject.parseObject(message);
        String productKey = msg.getString("product_key");
        String mac = msg.getString("mac").toUpperCase();
        String did = msg.getString("did");
        long latestOnlineTime = msg.getLong("created_at");
        //保持数据库设备数据只有一条
        List<DeviceInfoEntity> deviceInfoEntities =  deviceInfoEntityRepo.findDeviceListByMac(mac,transNewToOld(mac));
        if(deviceInfoEntities.size() > 0){
            DeviceInfoEntity deviceInfoEntity = deviceInfoEntities.get(0);
            if(deviceInfoEntity.getSource() == 1){
                deviceInfoEntity.setOnline(true);
                deviceInfoEntity.setLatestOnlineTime(latestOnlineTime);
                deviceInfoEntity.setDid(did);
                deviceInfoEntityRepo.save(deviceInfoEntity);
            }else{
                return;
            }
        }else{
            DeviceInfoEntity deviceInfoEntity = new DeviceInfoEntity();
            deviceInfoEntity.createOtherSourceDevice(productKey, mac, did, true);
            deviceInfoEntity.setLatestOnlineTime(latestOnlineTime);
            deviceInfoEntityRepo.save(deviceInfoEntity);
        }
        calculateTime(mac);
    }

    /**
     * 开机情况下计算滤网时间
     * @param mac
     */
    public void calculateTime(String mac) {
        String key = pathKey + mac;
        //记录下当前开机时间
        objectRedis.add(key, new Date().getTime());
    }

    private String transNewToOld(String newMac){
        StringBuilder stringBuilder = new StringBuilder();
        int begin = 0;
        int end = 2;
        int len = newMac.length()/2;
        for(int i=0; i<len; i++){
            stringBuilder.append(newMac.substring(begin,end)+":");
            begin = begin+2;
            end = end+2;
        }
        return stringBuilder.subSequence(0,stringBuilder.length()-1).toString();
    }
}
